package org.nstack.compute.vm;

import org.springframework.beans.factory.annotation.Autowire;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Configurable;
import org.nstack.core.cloudbus.CloudBus;
import org.nstack.core.cloudbus.CloudBusCallBack;
import org.nstack.core.errorcode.ErrorFacade;
import org.nstack.header.core.workflow.FlowTrigger;
import org.nstack.header.core.workflow.NoRollbackFlow;
import org.nstack.header.host.HostConstant;
import org.nstack.header.message.MessageReply;
import org.nstack.header.vm.VmAttachNicOnHypervisorMsg;
import org.nstack.header.vm.VmInstanceConstant;
import org.nstack.header.vm.VmInstanceSpec;
import org.nstack.header.vm.VmNicInventory;

import java.util.Map;


@Configurable(preConstruction = true, autowire = Autowire.BY_TYPE)
public class VmAttachNicOnHypervisorFlow extends NoRollbackFlow {

    @Autowired
    private CloudBus bus;
    @Autowired
    private ErrorFacade errf;

    @Override
    public void run(final FlowTrigger trigger, Map data) {
        VmInstanceSpec spec = (VmInstanceSpec) data.get(VmInstanceConstant.Params.VmInstanceSpec.toString());
        VmNicInventory nic = spec.getDestNics().get(0);

        VmAttachNicOnHypervisorMsg msg = new VmAttachNicOnHypervisorMsg();
        msg.setHostUuid(spec.getVmInventory().getHostUuid());
        msg.setNicInventory(nic);
        bus.makeTargetServiceIdByResourceUuid(msg, HostConstant.SERVICE_ID, msg.getHostUuid());
        bus.send(msg, new CloudBusCallBack(trigger) {
            @Override
            public void run(MessageReply reply) {
                if (!reply.isSuccess()) {
                    trigger.fail(reply.getError());
                } else {
                    trigger.next();
                }
            }
        });
    }
}
